<template>
	<view>
		<cu-custom
			:key="'header'+headerKey"
			:bgColor="userType == '20' ? 'bg-gradual-blue-light' : 'bg-gradual-orange-light'"
			:isCity="true"
			:areaName="areaName"
			title="金华人社"
			@areaChange="areaChangeTap"
		></cu-custom>
		<scroll-view scroll-y>
			<view>
				<swiper
					v-if="swiperList && swiperList.length > 0"
					class="screen-swiper square-dot"
					:indicator-dots="true"
					:circular="true"
					:autoplay="true"
					interval="5000"
					duration="500"
				>
					<swiper-item v-for="(item, index) in swiperList" :key="index" @tap="swiperTap(item)">
						<image :src="item.url" mode="aspectFill" v-if="item.type == 'image'"></image>
						<video :src="item.url" autoplay loop muted :show-play-btn="false" :controls="false" objectFit="cover" v-if="item.type == 'video'"></video>
					</swiper-item>
				</swiper>
				<view v-if="noticeList && noticeList.length > 0" class="bg-white">
					<view style="display: flex;align-items: center;height: 82rpx;line-height: 82rpx;justify-content: space-between; vertical-align:middle;padding: 0 10rpx 0 30rpx">
						<view style="display: flex;align-items: center;justify-content: flex-start; vertical-align:middle;">
							<image src="/static/iconfont/zuixinzixun.png" style="padding-right:20rpx;width: 140rpx;height: 32rpx;border-right: 1rpx solid #DFDFDF;"></image>
						</view>
						<zh-noticeBar type="vert" :showIcon="false" :list="noticeList" @showMore="noticeMoreTap" @itemClick="noticeClick"></zh-noticeBar>
					</view>
				</view>
			</view>
			<view class="margin-top-sm">
				<view class="cu-bar bg-white ">
					<view class="action" style="font-size: 32rpx;font-weight:bold;"><text>常用应用</text></view>
					<view class="action text-gray" style="font-size: 24rpx;" @tap="commonMenuMoreTap">更多</view>
				</view>
			</view>
			<view v-if="commonList && commonList.length > 0" style="padding-top: 10rpx;" class="cu-list grid" :class="['col-' + gridCol, gridBorder ? '' : 'no-border']">
				<view class="cu-item" v-for="(item, index) in commonList" :key="index" v-if="index < gridCol * 2" @tap="menuTap(item)">
					<view style="display: flex;align-items: center;justify-content: center;">
						<view style="align-items: center;">
							<view style="display: flex;align-items: center;justify-content: center;vertical-align:middle;">
								<view
									class="round"
									style="width: 84rpx;height: 84rpx;display:flex;position: relative; flex-direction: column;"
									:style="[{ backgroundColor: item.bgColor }]"
								>
									<view style="right: auto;left: 50%;margin-left: 20rpx" class=" cu-tag badge" v-if="item.badge && item.badge != 0">
										<block v-if="item.badge != 1">{{ item.badge > 99 ? '99+' : item.badge }}</block>
									</view>
									<view
										style="position: relative;width: 100%;display:block;font-size: 42rpx;margin-top: 6rpx;"
										:class="[item.icon]"
										:style="[{ color: item.color ? item.color : '' }]"
									></view>
								</view>
							</view>
							<text style="display:block;font-size: 28rpx;line-height: 30rpx;padding-top: 15rpx;">{{ item.title }}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="margin-top-sm bg-white">
				<view class="cu-bar">
					<view class="action" style="font-size: 32rpx;font-weight:bold;"><text>政策咨询</text></view>
				</view>
				<view v-if="policyAdviceList && policyAdviceList.length > 0" class="nav-list">
					<view
						class="nav-li"
						style="height: 156rpx;"
						v-for="(item, index) in policyAdviceList"
						:key="index"
						hover-class="none"
						:style="[
							{ animation: 'show ' + ((index + 1) * 0.2 + 1) + 's 1' },
							{ backgroundImage: item.bgUrl ? 'url(' + item.bgUrl + ')' : '' },
							{ backgroundColor: item.bgColor ? item.bgColor : '' }
						]"
						@tap="menuTap(item)"
					>
						<view style="font-size: 30rpx;font-weight:bold;padding: 10rpx 0 0 25rpx;" :style="[{ color: item.color ? item.color : '' }]">{{ item.title }}</view>
						<view style="padding-left: 25rpx;font-size: 22rpx;" :style="[{ color: item.color ? item.color : '' }]">{{ item.remarks }}</view>
					</view>
				</view>
			</view>
			<view class="margin-top-sm"></view>
		</scroll-view>
		<u-modal v-model="modelShow" :content="modelContent" :confirm-color="userType == '20' ? '#0081ff' : '#f37b1d'"></u-modal>
		<u-toast ref="uToast" />
		<w-picker
			:visible.sync="areaVisible"
			mode="selector"
			:options="areaData"
			:themeColor="userType == '20' ? '#0081ff' : '#f37b1d'"
			@confirm="onAreaChange($event)"
			:defaultProps="{ label: 'areaName', value: 'areaCode' }"
			ref="area"
		></w-picker>
	</view>
</template>

<script>

import store from '@/store';
import api from '@/api/society/home/home.js';
import util from '@/common/util/util.js';
// #ifdef MP-WEIXIN
import amap from '@/common/amap-wx.js';
// #endif
// #ifdef H5
import AMapLoader from '@amap/amap-jsapi-loader';
// #endif
import systemConfig from '@/common/config/systemConfig.js';
export default {
	onShow() {
		this.headerKey += 1;
	},
	onLoad: function(option) {
		// #ifdef MP-WEIXIN
		this.amapPlugin = new amap.AMapWX({
			key: systemConfig.amapKey
		});
		// #endif
		// #ifdef H5
		let browerInfo = store.state.hh_browerInfo;
		if (!browerInfo) {
			browerInfo = util.getBrowerInfo()
			this.$u.vuex('hh_browerInfo', browerInfo)
		}
		// if (browerInfo) {
		// 	let type = browerInfo.browserType
		// 	if (type == 'zlb' || type == 'zlb-alipay'||type == 'alipay') {
		// 		ZWJSBridge.getLocation() .then((result) => {
		// 				aplus_queue.push({ 'action':'aplus.record', 'arguments':
		// 				['/yourTrackerEventCode', 'CLK',
		// 				{ gdLbs:'高德 GPS 定位',
		// 				long:data.longitude,
		// 				lati:data.latitude,
		// 				site_id:'',
		// 				userType:this.userType=='30'?'企业':'个人',
		// 				zlb_serviceId:'',
		// 				pageId:'home',
		// 				pageName:this.title?this.title:'金华人社',
		// 				miniAppId:'2001101270' }] })
		// 		}).catch((error) => { console.log(error); });
		// 	}
		// }
		if (window.AMap) {
			this.h5Geolocation();
		} else {
			AMapLoader.load({
				key: systemConfig.amapH5Key, // 申请好的Web端开发者Key，首次调用 load 时必填
				version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
				plugins: ['AMap.Geolocation'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
			})
				.then(AMap => {
					this.h5Geolocation();
				})
				.catch(e => {
					console.log(e);
				});
		}
		// #endif
		if (this.userType == '30') {
			uni.setTabBarStyle({
				selectedColor: '#f37b1d'
			});
			uni.setTabBarItem({
				index: 0,
				selectedIconPath: 'static/tabBar/home-fill-company.png'
			});
			uni.setTabBarItem({
				index: 1,
				selectedIconPath: 'static/tabBar/news-fill-company.png'
			});
			uni.setTabBarItem({
				index: 2,
				selectedIconPath: 'static/tabBar/find-fill-company.png'
			});
			uni.setTabBarItem({
				index: 3,
				selectedIconPath: 'static/tabBar/my-fill-company.png'
			});
		}
		if (option) {
			let clientId = option.clientId;
			let token = option.token;
			let time = option.time;
			//#ifdef H5
			if(!clientId){
				clientId = util.getQueryString('clientId')
			}
			if(!token){
				token = util.getQueryString('token')
			}
			if(!time){
				time = util.getQueryString('time')
			}

			//#endif
			if (!store.state.hh_token) {
				this.clientId = clientId;
				this.token = token;
				uni.setStorageSync('hh_time', time);
			} else {
				if (time) {
					let cuTime = uni.getStorageSync('hh_time');
					if (time != cuTime) {
						this.clientId = clientId;
						this.token = otoken;
						uni.setStorageSync('hh_time', time);
					}
				}
			}
		}
	},
	onReady() {
		const vim = this;
		//银行等第三方登录
		if (this.clientId && this.token) {
			const data = {};
			data.clientId = this.clientId;
			data.token = this.token;
			this.$http
				.post(api.temporaryToken, data)
				.then(res => {
					this.$u.vuex('hh_token', res.result.accessToken);
					this.$u.vuex('hh_openid', res.result.openId);
					const sessionData = {};
					this.$http
						.post(api.getSessionInfo, sessionData)
						.then(res => {
							const sessionInfo = res.result;
							this.$u.vuex('hh_userType', sessionInfo.userType);
							this.$u.vuex('hh_user', sessionInfo);
							this.userType = sessionInfo.userType;
							this.init();
						})
						.catch(error => {
							this.$Router.replaceAll({ name: 'login' });
						});
				})
				.catch(error => {
					this.$u.vuex('hh_token', '');
					if (error.code) {
						if (error.code == 10003) {
							this.$Router.replaceAll({ name: 'register' });
						}
					}
					//this.$Router.replaceAll({ name:'login'})
				});
		} else {
			this.init();
		}
	},
	data() {
		return {
			headerKey: 0,
			amapPlugin: null,
			areaVisible: false,
			messageTimer: null,
			cardCur: 0,
			userType: store.state.hh_userType,
			areaCode: store.state.hh_areaCode,
			areaName: store.state.hh_areaName,
			noticeNumber: 0,
			noticeList: [{ title: '金华人社小程序体验版上线啦！' }],
			swiperList: [],
			gridCol: 4,
			gridBorder: false,
			clientId: null,
			token: null,
			commonList: [],
			policyAdviceList: [],
			modelShow: false,
			modelContent: '功能目前在测试中，尚未开放',
			areaData: [
				{ areaCode: '330700', areaName: '金华市' },
				{ areaCode: '330702', areaName: '婺城区' },
				{ areaCode: '330703', areaName: '金东区' },
				{ areaCode: '330723', areaName: '武义县' },
				{ areaCode: '330726', areaName: '浦江县' },
				{ areaCode: '330727', areaName: '磐安县' },
				{ areaCode: '330781', areaName: '兰溪市' },
				{ areaCode: '330782', areaName: '义乌市' },
				{ areaCode: '330783', areaName: '东阳市' },
				{ areaCode: '330784', areaName: '永康市' }
			]
		};
	},
	methods: {
		init() {
			//20秒轮询一次
			const _that = this;
			if (store.state.hh_token) {
				this.messageTimer = setInterval(function() {
					_that.$http
						.post(api.getUserNoReadMessageCnt, {})
						.then(res => {
							if (res.result) {
								let cnt = '0';
								let flag = true;
								if (res.result > 0 && res.result <= 99) {
									cnt = res.result.toString();
								} else if (res.result > 99) {
									cnt = '99+';
								} else {
									flag = false;
									uni.removeTabBarBadge({
										index: 1
									});
								}
								if (flag) {
									uni.setTabBarBadge({
										index: 1,
										text: cnt
									});
								}
							}
						})
						.catch(error => {
							uni.removeTabBarBadge({
								index: 1
							});
						});
				}, 20000);
			} else {
				clearInterval(this.messageTimer);
			}
			// #ifdef MP-WEIXIN
			this.isGetLocation();
			// #endif
			setTimeout(() => {
				const bannerData = {};
				bannerData.userType = this.userType;
				bannerData.bannerType = 'home';
				if (store.state.hh_user) {
					if (this.userType == '20') {
						bannerData.idcard = store.state.hh_user.idcard;
					} else if (this.userType == '30') {
						bannerData.orgId = store.state.hh_user.orgId;
					}
				}
				this.$http
					.post(api.getHomeBanner, bannerData)
					.then(res => {
						this.swiperList = res.result;
					})
					.catch(error => {
						_that.$refs.uToast.show({
							title: error.message,
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: 'warning',
							position: 'top',
							// 如果不需要图标，请设置为false
							icon: false
						});
					});
			}, 50);
			setTimeout(() => {
				const noticeData = {};
				noticeData.pageNum = 1;
				noticeData.pageSize = 5;
				noticeData.articleType = 'notice';
				noticeData.areaCode = this.areaCode;
				noticeData.showPosition = 'home';
				this.$http
					.post(api.getHomeNotice, noticeData)
					.then(res => {
						this.noticeList = res.result.list;
					})
					.catch(error => {
						_that.$refs.uToast.show({
							title: error.message,
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: 'warning',
							position: 'top',
							// 如果不需要图标，请设置为false
							icon: false
						});
					});
			}, 50);
			this.queryMenu();
		},
		areaChangeTap() {
			this.areaVisible = true;
		},
		isNotNull(value) {
			console.log(value);
			if (value && value != 'undefined') {
				return true;
			} else {
				return false;
			}
		},
		onAreaChange(e) {
			console.log(e);
			if (e) {
				this.areaCode = e.value;
				this.areaName = e.result;
				if (store.state.hh_areaCode != e.value) {
					this.queryMenu();
				}
				this.$u.vuex('hh_areaCode', e.value);
				this.$u.vuex('hh_areaName', e.result);
			}
		},
		queryMenu() {
			const menuDate = {};
			if (this.userType == '30') {
				menuDate.menuPro = 'company';
			} else if (this.userType == '20') {
				menuDate.menuPro = 'person';
			} else {
				menuDate.menuPro = 'manager';
			}
			const vim = this;
			menuDate.areaCode = this.areaCode;
			menuDate.clientId = this.clientId;
			setTimeout(() => {
				const commonData = Object.assign({}, menuDate);
				commonData.menuType = 'common_used';
				this.$http
					.post(api.getMenuList, commonData)
					.then(res => {
						this.commonList = res.result;
					})
					.catch(error => {
						vim.$refs.uToast.show({
							title: error.message,
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: 'warning',
							// 如果不需要图标，请设置为false
							position: 'top',
							icon: false
						});
					});
			}, 50);
			setTimeout(() => {
				const policyData = Object.assign({}, menuDate);
				policyData.menuType = 'policy_advice';
				this.$http
					.post(api.getMenuList, policyData)
					.then(res => {
						this.policyAdviceList = res.result;
					})
					.catch(error => {});
			}, 50);
		},
		// #ifdef H5
		h5Geolocation() {
			let AMap = window.AMap;
			const vim = this;
			AMap.plugin('AMap.Geolocation', function() {
				let geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 10000, //超过10秒后停止定位，默认：无穷大
					maximumAge: 0, //定位结果缓存0毫秒，默认：0
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					showButton: false, //显示定位按钮，默认：true
					buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
					showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
					panToLocation: false, //定位成功后将定位到的位置作为地图中心点，默认：true
					zoomToAccuracy: false //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				});
				geolocation.getCurrentPosition(function(status, result) {
					if (status == 'complete') {
						onComplete(result);
					} else {
						onError(result);
					}
				});

				function onComplete(result) {
					// result是具体的定位信息
					const addressComponent = result.addressComponent;
					if (addressComponent && addressComponent.adcode) {
						vim.$u.vuex('hh_areaCode', addressComponent.adcode);
						vim.areaCode = addressComponent.adcode;
					} else {
						vim.$u.vuex('hh_areaCode', '330700');
						vim.areaCode = '330700';
					}
					if (addressComponent && addressComponent.district) {
						vim.$u.vuex('hh_areaName', addressComponent.district);
						vim.areaName = addressComponent.district;
					} else {
						vim.$u.vuex('hh_areaName', '金华市');
						vim.areaName = '金华市';
					}

					if (vim.areaCode == '330700' && result.position.lng && result.position.lat) {
						AMap.plugin('AMap.Geocoder', function() {
							var geocoder = new AMap.Geocoder({
								// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
								city: '全国'
							});
							var lnglat = [result.position.lng, result.position.lat];
							geocoder.getAddress(lnglat, function(status, data) {
								if (status === 'complete' && data.info === 'OK') {
									const regeocodeData = data.regeocode;
									if (regeocodeData) {
										const addressComponent = regeocodeData.addressComponent;
										if (addressComponent) {
											if (addressComponent.adcode) {
												vim.$u.vuex('hh_areaCode', addressComponent.adcode);
												vim.areaCode = addressComponent.adcode;
											}
											if (addressComponent.district) {
												vim.$u.vuex('hh_areaName', addressComponent.district);
												vim.areaName = addressComponent.district;
											}
										}
									}
								}
							});
						});
					}
				}

				function onError(result) {
					// 定位出错
					vim.$u.vuex('hh_areaCode', '330700');
					vim.areaCode = '330700';
					vim.$u.vuex('hh_areaName', '金华市');
					vim.areaName = '金华市';
				}
			});
		},
		// #endif
		// #ifdef MP-WEIXIN
		getRegeo() {
			this.amapPlugin.getRegeo({
				success: data => {
					if (data) {
						const regeocodeData = data[0].regeocodeData;
						if (regeocodeData) {
							const addressComponent = regeocodeData.addressComponent;
							if (addressComponent) {
								if (addressComponent.adcode) {
									this.$u.vuex('hh_areaCode', addressComponent.adcode);
									this.areaCode = addressComponent.adcode;
								}
								if (addressComponent.district) {
									this.$u.vuex('hh_areaName', addressComponent.district);
									this.areaName = addressComponent.district;
								}
							}
						}
					}
				},
				fail: info => {
					this.modelContent = '您拒绝了位置授权，系统不能自动为您推荐当前所在地区特色业务，如需办理当地特色社保业务，请点击左上角选择地区';
					this.modelShow = true;
				}
			});
		},
		isGetLocation(a = 'scope.userLocation') {
			// 3. 检查当前是否已经授权访问scope属性，参考下截图
			var _this = this;
			uni.getSetting({
				success(res) {
					console.log(res);
					console.log(res.authSetting[a]);
					const authFlag = res.authSetting[a];
					if (!authFlag) {
						//3.1 每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置
						if (authFlag == null || authFlag == undefined) {
							_this.getRegeo();
						} else {
							wx.showModal({
								title: '提示',
								content: '需要获取您的位置信息，用于推荐当地可办理的社保业务，请授权',
								cancelText: '不授权',
								cancelColor: '#999',
								confirmText: '授权',
								confirmColor: '#0081ff',
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success(res) {
												_this.getRegeo();
											},
											fail(res) {
												_this.modelContent = '授权失败，系统不能自动为您推荐当前所在地区特色业务，如需办理当地特色社保业务，请点击左上角选择地区';
												_this.modelShow = true;
											}
										});
									} else if (res.cancel) {
										_this.getRegeo();
									}
								}
							});
						}
					} else {
						_this.getRegeo();
					}
				}
			});
		},
		// #endif
		swiperTap(item) {
			if (item.linkType) {
				// 点击轮播图
				this.modelContent = '功能目前在测试中，尚未开放';
				this.modelShow = true;
			}
		},
		menuTap(item) {
			// 点击菜单
			if (item.linkType) {
				if (item.linkType == 'router') {
					if (item.linkName) {
						let params = {};
						if (item.param1) {
							//自定义参数1为请求参数，不为空时传入
							try {
								params = JSON.parse(item.param1);
							} catch (e) {
								this.modelContent = '请求参数（param1）配置必须是json格式';
								this.modelShow = true;
								return;
							}
						}
						params.headerTitle = item.title; //标题
						params.menuId = item.menuId; //菜单id
						params.serviceCode = item.serviceCode; //服务事项编码
						params.serviceName = item.serviceName; //服务事项名称

						let flag = false;
						for (var num in ROUTES) {
							const router = ROUTES[num];
							if (item.linkName == router.name) {
								flag = true;
								break;
							}
						}
						if (flag) {
							this.$Router.push({ path: item.linkPath, query: params });
						} else {
							this.modelContent = '功能配置异常，未找到跳转页面';
							this.modelShow = true;
						}

					} else {
						this.modelContent = '功能目前在测试中，尚未开放';
						this.modelShow = true;
					}
				} else if (item.linkType == 'h5') {
					if (item.linkUrl) {
						this.gotoOhterPage(item);
					} else {
						this.modelContent = '功能目前在测试中，尚未开放';
						this.modelShow = true;
					}
				} else {
					this.modelContent = '功能目前在测试中，尚未开放';
					this.modelShow = true;
				}
			} else {
				this.modelContent = '功能目前在测试中，尚未开放';
				this.modelShow = true;
			}
		},
		gotoOhterPage(item) {
			const url = item.linkUrl;
			if (url) {
				let params = {};
				params.headerTitle = item.title; //标题
				params.menuId = item.menuId; //菜单id
				params.serviceCode = item.param2; //服务事项编码
				params.serviceName = item.param3; //服务事项名称

				params.url = encodeURIComponent(url);
				if (item.linkPath) {
					this.$Router.push({ path: item.linkPath, query: params });
				} else {
					this.$Router.push({ path: '/pages/system/web-view/webViewLogin', query: params });
				}
			} else {
				this.modelContent = '没有传入跳转的链接';
				this.modelShow = true;
			}
		},
		commonMenuMoreTap() {
			// 点击更多常用菜单
			this.modelContent = '功能目前在测试中，尚未开放';
			this.modelShow = true;
		},
		noticeMoreTap() {
			// 点击更多公共
			const data = {};
			data.articleType = 'notice';
			data.headerTitle = '新闻公告';
			data.showPosition = 'home';
			this.$Router.push({ path: '/pages/system/article/article', query: data });
		},
		noticeClick(item) {
			this.$Router.push({ path: '/pages/system/article/articleDetail', query: item });
		},
		startMove() {
			// eslint-disable-next-line
			let timer = setTimeout(() => {
				if (this.noticeNumber == this.noticeList.length - 1) {
					this.noticeNumber = 0;
				} else {
					this.noticeNumber += 1;
				}
				this.startMove();
			}, 3000); // 滚动不需要停顿则将2000改成动画持续时间
		}
	},
	mounted() {
		this.startMove();
	},
	computed: {
		showNoticeList() {
			let list = [];
			const noticeSize = this.noticeList.length;
			if (noticeSize <= 0) {
				return [];
			}
			if (noticeSize <= 1) {
				return this.noticeList;
			}
			list.push(this.noticeList[this.noticeNumber]);
			/***
				if(this.noticeNumber==this.noticeList.length-1){
					list.push(this.noticeList[0])
				}else{
					list.push(this.noticeList[this.noticeNumber+1])
				}***/
			return list;
		}
	},
	beforeDestroy() {
		if (this.messageTimer) {
			clearInterval(this.messageTimer); // 在Vue实例销毁前，清除我们的定时器
		}
	}
};
</script>

<style></style>
